<template>
<div>
  <!--面包屑导航区-->
  <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>权限管理</el-breadcrumb-item>
    <el-breadcrumb-item>角色列表</el-breadcrumb-item>
  </el-breadcrumb>

  <!--卡片视图-->
  <el-card>
    <!-- 添加角色按钮区域-->
    <el-row>
      <el-col>
        <el-button type="primary" @click="addRolesButton">添加角色</el-button>
      </el-col>
    </el-row>

    <!--角色列表-->
    <el-table :data='rolesList' border stripe>
      <!--展开列-->
      <el-table-column type="expand" label="">
        <template slot-scope="scope">
          <el-row v-for='(item1,i1) in scope.row.children' :key="item1.id" :class="['bdbottom','vcenter' ,i1===0 ? 'bdtop':'']">
            <!--渲染一级权限 列-->
            <el-col :span='5'>
              <el-tag closable @close='removeRightByid(scope.row,item1.id)'>{{item1.authName}}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <!--渲染二级权限 和三级列  列-->
            <el-col :span='19'>
              <!--通过 循环 嵌套 渲染二级权限-->
              <el-row v-for="(item2,i2) in item1.children" :key="item2.id" :class="['vcenter',i2===0 ? '':'bdtop']">
                <el-col :span="6">
                  <el-tag type="success" closable @close='removeRightByid(scope.row,item2.id)'>{{item2.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="18">
                  <el-tag type='warning' v-for="(item3) in item2.children" :key="item3.id" closable @close='removeRightByid(scope.row,item3.id)'>{{item3.authName}}</el-tag>

                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <!--索引列-->
      <el-table-column type="index" label="#"></el-table-column>
      <el-table-column label="角色名称" prop="roleName"></el-table-column>
      <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
      <el-table-column label="操作" width="300px">
        <template slot-scope="scope">
          <el-button type="primary" @click="showEditDialog(scope.row.id)" icon="el-icon-edit" size='mini'>编辑</el-button>
          <el-button type="danger" @click="removeRolesById(scope.row.id)" icon="el-icon-delete" size='mini'>删除</el-button>
          <el-button type="warning" @click="showSetRightDialog(scope.row)" icon="el-icon-setting" size='mini'>分配权限</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
  <!--添加角色对话框-->
  <el-dialog title="添加角色" :visible.sync="addRolesVisible" width="50%" @close='addRolesDialogClose'>
    <el-form :model="addRolesForm" ref='addRolesFormRef' :rules='addRolesFormRules' label-width="80px">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="addRolesForm.roleName"></el-input>
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDesc">
        <el-input v-model="addRolesForm.roleDesc"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer">
      <el-button @click="addRolesVisible = false">取 消</el-button>
      <el-button type="primary" @click="addRoles">确 定</el-button>
    </span>
  </el-dialog>
  <!-- 编辑角色对话框 -->
  <el-dialog title="修改角色信息" :visible.sync="editRolesVisible" width="50%" @close='editRolesDialogClose'>
    <!--角色对话框表单-->
    <el-form :model="rolesForm" ref="rolesFormRef" :rules="rolesFormRules" label-width="80px">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="rolesForm.roleName"></el-input>
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDesc">
        <el-input v-model="rolesForm.roleDesc"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer">
      <el-button @click="editRolesVisible = false">取 消</el-button>
      <el-button type="primary" @click="editRoles">确 定</el-button>
    </span>
  </el-dialog>

  <!--分配权限对话框-->
  <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close='setRightDialogClosed'>
    <!--树型控件-->
    <el-tree :data="rightList" :props="treeProps" show-checkbox node-key='id' :default-checked-keys='defKeys' ref="treeRef" default-expand-all></el-tree>

    <span slot="footer" class="dialog-footer">
      <el-button @click="setRightDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="allotRights">确 定</el-button>
    </span>
  </el-dialog>
</div>
</template>

<script>
export default {
  data() {
    return {
      // 所有角色列表数据
      rolesList: [],
      // 所有权限的数据
      rightList: [],
      // 编辑角色form 信息对象
      rolesForm: {},
      // 添加角色form 信息对象
      addRolesForm: {
        roleName: '',
        roleDesc: ''
      },
      // 树型树 默认选中的节点Id值 数组
      defKeys: [],
      // 当前即将分配权限的 角色ID
      roleId: '',
      // 编辑角色信息对象效验规则
      rolesFormRules: {
        roleName: [{
          required: true,
          message: "角色信息不能为空",
          trigger: "blur",
        }],
        roleDesc: [{
          required: true,
          message: "角色描述不能为空",
          trigger: "blur",
        }]
      },
      // 添加角色信息对象校验规则
      addRolesFormRules: {
        roleName: [{
          required: true,
          message: "角色信息不能为空",
          trigger: "blur",
        }],
        roleDesc: [{
          required: true,
          message: "角色描述不能为空",
          trigger: "blur",
        }]
      },

      // 树型控件绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 用于编辑角色对话框状态
      editRolesVisible: false,
      // 用于添加角色对话框状态
      addRolesVisible: false,
      // 用于分配权限对话框
      setRightDialogVisible: false
    }
  },

  created() {
    this.getRolesList()
  },

  methods: {
    // 获取所有角色的列表
    async getRolesList() {
      const {
        data: res
      } = await this.$http.get('roles')

      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败');

      this.rolesList = res.data
      // console.log(this.rolesList)
    },
    // 监听角色编辑对话框消失
    editRolesDialogClose() {
      this.$refs.rolesFormRef.resetFields()
    },
    // 监听添加角色对话框消失
    addRolesDialogClose() {
      this.$refs.addRolesFormRef.resetFields()
    },
    // 监听 分配权限对话框的关闭权限 对话框消失

    setRightDialogClosed() {
      this.defKeys = []
    },
    // 角色编辑对话框
    async showEditDialog(id) {
      this.editRolesVisible = !this.editRolesVisible

      // 查询角色id 拿到角色信息
      const {
        data: res
      } = await this.$http.get(`roles/${id}`)
      if (res.meta.status !== 200) return this.$message('获取角色信息失败')
      console.log(res.data)
      this.rolesForm = res.data
    },
    // 点击修改角色信息
    editRoles() {
      console.log(1)

      this.$refs.rolesFormRef.validate(async value => {
        if (!value) return

        const {
          data: res
        } = await this.$http.put(`roles/${this.rolesForm.roleId}`, {
          roleName: this.rolesForm.roleName,
          roleDesc: this.rolesForm.roleDesc
        })
        if (res.meta.status !== 200) return this.$message.error('修改失败');

        this.editRolesVisible = false;
        this.$message.success('修改成功')

        this.getRolesList()

      })
    },

    // 点击 添加角色信息
    addRoles() {
      this.$refs.addRolesFormRef.validate(async value => {
        if (!value) return;
        const {
          data: res
        } = await this.$http.post('roles', this.addRolesForm)
        if (res.meta.status !== 201) return this.$message.error('添加失败');
        this.addRolesVisible = false;
        this.$message.success(res.meta.msg)
        this.getRolesList()
      })
    },
    // 点击删除 角色信息
    async removeRolesById(id) {
      try {
        const confirm = await this.$confirm(
          "此操作将永久删除该角色, 是否继续?",
          "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
        const {
          data: res
        } = await this.$http.delete(`roles/${id}`)

        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg);

        this.getRolesList()

      } catch (err) {
        this.$message.info("已经取消删除");
      }

    },
    // 点击添加角色按钮 唤醒对话框
    addRolesButton() {
      this.addRolesVisible = !this.addRolesVisible
    },

    // 根据 id 删除对应的权限
    async removeRightByid(role, rightId) {
      // 弹框 提示用户是否要删除
      try {
        const confirm = await this.$confirm(
          "此操作将永久删除该用户, 是否继续?",
          "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
        const {
          data: res
        } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
        // console.log(roel, rightId)
        if (res.meta.status !== 200) return this.$message.error('操作失败')

        role.children = res.data

        this.$message.success(res.meta.msg)
      } catch (err) {
        this.$message.info('取消删除')
      }
    },
    // 展示分配权限的对话框
    async showSetRightDialog(role) {
      this.roleId = role.id

      // 获取所有权限数据
      const {
        data: res
      } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限数据失败')
      this.rightList = res.data
      // console.log(this.rightList)

      // 递归获取三级节点
      this.getLeafKeys(role, this.defKeys)

      this.setRightDialogVisible = true

    },

    // 点击 为角色分配权限 对话框 确定按钮
    async allotRights() {
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      const idStr = keys.join(',')

      const {
        data: res
      } = await this.$http.post(`roles/${this.roleId}/rights`, {
        rids: idStr
      })
      if (res.meta.status !== 200) return this.$message.error('分配权限失败');
      this.getRolesList()
      this.setRightDialogVisible = false

      this.$message.success('分配权限成功')

    },

    // 通过递归的形式, 获取角色下所有三级权限的 id, 并保存到 defKeys 数组中
    getLeafKeys(node, arr) {
      // 如果当前 节点不包含 children属性 则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }

      node.children.forEach(item => this.getLeafKeys(item, arr))
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
